package com.keyware.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 此类描述的是：   下载文件
 * @author: 赵亚舟   
 * @version: 2018年11月13日 上午9:48:49
 */
public class FileDownloadUtils {
	/**
	 * 
	 * @Title: downLoadBrowser
	 * @Description: 	下载文档
	 * @param request
	 * @param response
	 * @param fileName	文档名称
	 * @param fileType	文档格式 ：.doc/.docx/其他任意格式
	 * @param outputStream	文档输出流
	 * @author 赵亚舟
	 * @return void
	 */
	public static void downLoadBrowser(HttpServletRequest request, HttpServletResponse response, String fileName,String fileType, OutputStream outputStream){
		ByteArrayOutputStream byteArrayOutputStream  = null;
		OutputStream outputStreamDownload  = null;
		try {
			response.reset();
			response.resetBuffer();
			if (request.getHeader("user-agent").toLowerCase().contains("msie")||request.getHeader("user-agent").toLowerCase().contains("like gecko") ) {
				response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("GB2312"), "ISO8859-1" ) +fileType+ "\"");
			}else{
				response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("utf-8"), "ISO8859-1" ) +fileType+ "\"");
			}
			response.setContentType("application/octet-stream");
			response.setContentType("text/html;charset=UTF-8");
			byteArrayOutputStream = (ByteArrayOutputStream) outputStream;
			byte[] date = byteArrayOutputStream.toByteArray();
			outputStreamDownload = response.getOutputStream();
			outputStreamDownload.write(date);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(byteArrayOutputStream != null){
					byteArrayOutputStream.close();
				}
				if(outputStreamDownload != null){
					outputStreamDownload.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
